package com.example.clock_demo.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.clock_demo.dto.SchedulingMonthlyDTO;
import com.example.clock_demo.service.SchedulingService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.YearMonth;
import java.util.List;

import com.example.clock_demo.common.Result;

import static org.reflections.Reflections.log;
import org.springframework.security.access.prepost.PreAuthorize;

@RestController
@RequestMapping("/scheduling")
@Api(tags = "排班管理接口")
public class SchedulingController {


    @Autowired
    SchedulingService schedulingService;
    /**
     * 导入排班数据
     */
    @PostMapping("/import-scheduling")
    @ApiOperation("通过Excel导入月度排班数据")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<String> importScheduling(
            @ApiParam(value = "排班表Excel文件", required = true)
            @RequestParam("file") MultipartFile file,
            @ApiParam(value = "导入的月份 (格式: yyyy-MM)", required = true, example = "2025-07")
            @RequestParam("importMonth") @DateTimeFormat(pattern = "yyyy-MM") YearMonth importMonth) {

        if (file == null || file.isEmpty()) {
            return Result.error("上传失败，文件为空！");
        }
        try {
            // 这里调用 service 层的方法，service 会调用 EasyExcel 读取
            schedulingService.importScheduling(file, importMonth);
            return Result.success("排班数据导入成功");
        } catch (RuntimeException e) { // 捕获监听器中抛出的 RuntimeException
            log.error("导入排班数据失败：模板或数据格式不正确", e);
            // 返回具体的错误信息给用户
            return Result.error("导入失败: " + e.getMessage());
        } catch (Exception e) {
            log.error("导入排班数据失败：发生未知错误", e);
            return Result.error("导入失败: 服务器内部错误，请联系管理员。");
        }
    }

    /**
     * 分页查询排班信息（按员工月度统计）
     */
    @GetMapping("/monthly-page")
    @ApiOperation("分页查询排班信息")
    @PreAuthorize("hasAnyRole('ADMIN', 'EMPLOYEE')")
    public Result<IPage<SchedulingMonthlyDTO>> getMonthlySchedulingPage(
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "10") Long size,
            @RequestParam(required = false) String employeeName,
            @RequestParam(required = false) String teamName,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM") YearMonth scheduleMonth) {

        try {
            IPage<SchedulingMonthlyDTO> result = schedulingService.getMonthlySchedulingPage(current, size, employeeName, teamName, scheduleMonth);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("查询排班信息失败: " + e.getMessage());
        }
    }

    /**
     *导出排班表
     */
    @GetMapping("/export")
    @ApiOperation("导出排班表")
    @PreAuthorize("hasRole('ADMIN')")
    public void exportMonthlyScheduling(
            @RequestParam(required = false) String employeeName,
            @RequestParam(required = false) String teamName,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM") YearMonth scheduleMonth,
            HttpServletResponse response) throws IOException {
        schedulingService.exportMonthlyScheduling(employeeName, teamName, scheduleMonth, response);
    }


    @DeleteMapping("/delete-by-employees-and-month")
    @ApiOperation("根据员工工号列表和月份批量删除排班数据")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<String> deleteByEmployeeNumbersAndMonth(
            @ApiParam(value = "要删除排班的员工工号列表", required = true)
            @RequestBody List<String> employeeNumbers,
            @ApiParam(value = "排班月份 (格式: yyyy-MM)", required = true, example = "2025-07")
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM") YearMonth month) {
        try {
            if (employeeNumbers == null || employeeNumbers.isEmpty()) {
                return Result.error("员工工号列表不能为空");
            }
            schedulingService.deleteByEmployeeNumbersAndMonth(employeeNumbers, month);
            return Result.success("指定员工的月度排班数据删除成功");
        } catch (Exception e) {
            log.error("批量删除排班数据失败", e);
            return Result.error("删除失败: " + e.getMessage());
        }
    }
}